import Axios, { AxiosInstance } from 'axios'
import { Toast } from 'vant'

const baseURL = 'http://api.sanye666.top'

const service: AxiosInstance = Axios.create({
  baseURL,
  timeout: 20000 // 请求超时 20s
})

// request interceptor
service.interceptors.request.use(
  (config) => {
    // do something before request is sent
    return config
  },
  (error) => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  (response) => {
    const res = response.data

    if (res.code !== 200) {
      Toast.fail(res.message || res.msg || 'Error')
      return Promise.reject(res.message || res.msg || 'Error')
    }
    return res
  },
  (error) => {
    console.log(error) // for debug
    const message = error.message || error.msg || '未知错误'
    Toast.fail(message)
    return Promise.reject(error)
  }
)

export default service
